 <template>
  <div>
    <div>
      <p-form layout="inline" @keyup.enter.native="searchQuery">
        <p-row :gutter="24">
          <p-col :xl="8" :lg="7" :md="8" :sm="24">
            <p-form-item label="借出线体">
              <p-select v-model="OutWorkshop.textValue" style="width:180px" >
                <p-select-option  
                :disabled="value.disabled"
                :value="value.textValue" 
                @click="handleOutWorkshop(value)" 
                :key="value.codeValue"  
                v-for="value in info"
                >{{value.textValue}}</p-select-option>
              </p-select>
            </p-form-item>
          </p-col>
          <p-col :xl="8" :lg="7" :md="8" :sm="24" >
            <p-form-item label="借入车间">
              <p-select  v-model="InWorkshop.workroomname" style="width: 180px" >
                <p-select-option  
                :value="value.workroomname" 
                @click="handleWorkshop(value)" 
                :key="value.workroomno" 
                v-for="value in InWorkshopList"
                >{{value.workroomname}}</p-select-option>
              </p-select>
            </p-form-item>
          </p-col>
          <p-col :xl="8" :lg="7" :md="8" :sm="24">
            <p-form-item label="借入线体">
              <p-select v-model="Inline.linename" style="width: 180px" >
                <p-select-option 
                :value="value.linename" 
                @click="handlineShop(value)" 
                :key="value.classno" 
                v-for="value in InlineList">{{value.linename}}</p-select-option>
              </p-select>
            </p-form-item>
          </p-col>
        </p-row>
      </p-form>
    </div>
    <div>富余人力列表</div>
    <div style="margin-top:20px">
      <p-table
        ref="table"
        size="middle"
        bordered
        rowKey="empno"
        :columns="columns"
        :scroll="tableScroll"
        :dataSource="dataSource"
        :pagination="ipagination"
        :customRow="clickThenSelect"
      >
        <template slot="operation" slot-scope="text,record">
          <a @click="handleBorrow(record)">借入</a>
        </template>

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无此图片</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt="图片不存在"
            style="max-width:80px;font-size: 12px;font-style: italic;"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无此文件</span>
          <p-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="uploadFile(text)"
          >下载</p-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <p-divider type="vertical" />
          <p-dropdown>
            <a class="ant-dropdown-link">
              更多
              <p-icon type="down" />
            </a>
            <p-menu slot="overlay">
              <p-menu-item>
                <p-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </p-popconfirm>
              </p-menu-item>
              <template
                v-if="cgButtonLinkList && cgButtonLinkList.length>0"
                v-for="(btnItem,btnIndex) in cgButtonLinkList"
              >
                <p-menu-item :key=" 'cgbtnLink'+btnIndex " v-if="showLinkButton(btnItem,record)">
                  <a
                    href="javascript:void(0);"
                    @click="cgButtonLinkHandler(record,btnItem.buttonCode,btnItem.optType)"
                  >
                    <p-icon v-if="btnItem.buttonIcon" :type="btnItem.buttonIcon" />
                    {{ btnItem.buttonName }}
                  </a>
                </p-menu-item>
              </template>
            </p-menu>
          </p-dropdown>
        </span>
      </p-table>
    </div>
  </div>
</template>  

<script>
import { postAction, getAction, deleteAction } from "@/api/manage";
import { JeecgListMixin } from "@/mixins/JeecgListMixin";
import Vue from "vue";

// 下拉框联运
const factoryData = ["车间借调", "线体借调"];
const sonData = {
  车间借调: ["借出车间"],
  线体借调: ["借出线体"],
};
export default {
  name: "",
  mixins: [JeecgListMixin],
  
  data() {
    return {
      //借入人员
      humanBorrow:{
        	"empno": "",
          "lineBorrowname": "",
          "lineBorrowno": "",
          "lineLendname": "",
          "lineLendno": "",
          "secondmentDate": "",
          "secondmentScope": 0,
          "secondmentType": 0,
          "workroomBorrowname": "",
          "workroomBorrowno": "",
          "workroomLendname": "",
          "workroomLendno": ""
      },
      //线体车间信息
      info:{
        	"lines": {},
		      "workrooms": {}
      },

       // 用户数据
      OutWorkshop:"",//默认借出线体
      InWorkshop:'',   //默认借入车间
      Inline:'',      //默认借入线体
      OutData:{},//过滤后数据
      OutList:{},// 借出车间编码数据
      //下拉框联动
     factoryData  ,
      sonData,
      items: sonData[factoryData[0]],
      secondData: sonData[factoryData[0]][0],
      secondQueryParam: {
        //搜索关键字
        keyword: "",
        //借出线体(前端传入，用户选择线别，如果是车间借调不用传)
        lendLineno: "",
        //借出车间(前端传入，用户选择车间，如果是线别借调也需要传)
        limit: "",
        //页码
        pageNo: "",
        //借入车间编码
        workroomBorrowno: "",
        //借出车间编码
        workroomLendno: "",
      },
      EnhanceJS: "",
      cgButtonLinkList: [],
      cgButtonList: [],
      title: "", //存表名
      groupTag: [],
      queryInfo: [],
      code: "",
      // 表头
      columns: [],
      //列设置
      settingColumns: [],
      //列定义
      defColumns: [
        {
          title: "序号",
          dataIndex: "id",
          key: "rowIndex",
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          title: "线体",
          dataIndex: "lineno",
          key: "lineno",
          // width: "15%",
          align: "center",
          scopedSlots: { customRender: "lineno" },
        },
        {
          title: "工号",
          dataIndex: "empno",
          key: "empno",
          // width: "40%",
          align: "center",
          scopedSlots: { customRender: "empno" },
        },
        {
          title: "姓名",
          dataIndex: "empname",
          key: "empname",
          // width: "40%",
          align: "center",
          scopedSlots: { customRender: "empname" },
        },

        {
          title: "技能",
          dataIndex: "skillElements",
          key: "skillElements",
          align: "center",
         customRender: function (t, r, index) {
            let text=""
            t.forEach(item=>{ text+=item.name+","})
            return text
          },
        },
        {
          title: "岗位标记",
          dataIndex: "",
          align: "center",
        },
        {
          title: "已排工时",
          dataIndex: "",
          align: "center",
        },
        {
          title: "操作",
          dataIndex: "operation",
          key:"operation",
          align: "center",
          scopedSlots: { customRender: "operation" },
        },
      ],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ["10", "20", "50"],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      url: {
        //新增人员借调(借入)
        newHuman:"/mes-manufacture/mfStaffSecondment",
        //获取借出车间
        list: "/mes-manufacture/mfStaffSecondment/workrooms",
        //人员借调过滤条件
        staffSecondment:"/mes-manufacture/mfSurplusManpower/getFilter",
        //人员借调,富余人力列表
        moreHumanList:"/mes-manufacture/mfSurplusManpower/list/second",
        //获取当前用户信息
        currentUserUid: "/mes-manpower/mesHrEmployeeinfo/currUser",
      },
    };
  },
  created() {
    this.initColumns();
    this.setdefColumns();
    this.initData()
    this.getuserUidList()
  },
  methods: {
    //借入
    handleBorrow(row){
      this.OutList.empno=row.empno
      console.log(row)
      postAction(this.url.newHuman,this.OutList).then((res)=>{
       if(res.success){
         this.$message.success("借入成功");
         this.loadList()
       }
       if(res.code===510){
         this.$message.warning("借入失败");
       }
      })

    },
    handleOutWorkshop(val){
      if(val.codeValue==this.Inline.lineno){
        this.$message.error('借出线体和借入线体不能相同')
        setTimeout(() => {
          this.OutWorkshop.textValue=null
        }, 10);
      }else{
        this.OutWorkshop=val
        this.loadList()
        this.OutFilter(val)
      }

     
    },
    handleWorkshop(data){
      this.InWorkshop=data
      this.InlineList=data.lines
      this.Inline=data.lines[0]
    },
    handlineShop(data){
      this.Inline=data
    },
    loadList(){
      let obj={
        lendLineno:this.OutList.lineLendno,
        lendWorkroomno:this.OutList.workroomLendno
      }
      postAction(this.url.moreHumanList,obj).then((res)=>{
          if(res.success){
            this.dataSource = res.data;
          }
          if(res.code===510){
            this.$message.warning(res.msg);
          }
        })
    },
    // 过滤借出车间，线体数据
    OutFilter(val){
      if(val){
        if(this.OutData.length>0){
          this.OutData.forEach(item=>{
        item.lines.forEach(items=>{
          if(items.codeValue==val.codeValue){
             this.OutList={
               workroomLendno:item.workroomno,//借出车间编码
               workroomLendname:item.workroomname,   //借出车间名称
               lineLendno:items.codeValue,     //借出线体编码
               lineLendname:items.textValue,   //借出线体名称
               secondmentScope:1,            //借调范围(0:车间借调 1:线别借调)	
               secondmentType:0,            //借调类型(:0人员借调)
               lineBorrowno:this.Inline.lineno,    //借入线体编码
               lineBorrowname:this.Inline.linename,  //借入线体名称
               workroomBorrowno:this.InWorkshop.workroomno,  //借入车间编码
               workroomBorrowname:this.InWorkshop.workroomname,//借入车间名称
               empno:""                           //工号
               }
          }
        })
      })
      }else{
        this.$message.warning("暂无富裕人力,请先添加富裕人力！");
      }
      }
    },

    
    //人员借调过滤条件:线体
    initData(id){
      getAction(this.url.staffSecondment).then((res)=>{
        if(res.success){
          if(res.data.length>0){
            this.OutData=res.data
            let newData=[]
            res.data.forEach(item=>{
                item.lines.disabled=false
                newData.push(...item.lines)
                
            });
            this.info =newData
            this.OutWorkshop={codeValue:"",textValue:""}
            this.OutFilter(newData[0])
          }else{
            this.info=[]
            this.OutWorkshop={codeValue:"",textValue:""}
            this.OutFilter({codeValue:"",textValue:""})
          }
            
        }
        if(res.code===510){
          this.$message.warning(res.msg);
        }
      })
    },
    //uid 用户
    getuserUidList(){
          getAction(this.url.currentUserUid,{ sysCode: "mes" }).then(res=>{
          if(res.success){
            this.InWorkshop=this.getWorkrooms(res.data)[0]
            this.InWorkshopList=this.getWorkrooms(res.data)
            this.InlineList=this.getWorkrooms(res.data)[0].lines
            this.Inline=this.InWorkshop.lines[0]
          }
          if(res.code===510){
            this.$message.warning() 
          }
      })
    },


    clickThenSelect(record) {
      return {
        on: {
          click: () => {
            // this.onSelectChange(record.id.split(","), [record]);
          },
        },
      };
    },
    tableScroll: function () {
      if (this.columns.length > 13) {
        return { x: this.columns.length * 150 - 450 };
      }
    },
    setdefColumns() {
      if (this.columns.length > 13) {
        let arrLength = this.columns.length - 1;
        this.columns.forEach((item, index) => {
          item["width"] = 130;
        });
        this.columns[arrLength]["fixed"] = "right";
        this.columns[0]["fixed"] = "left";
        this.columns[1]["fixed"] = "left";
      }
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');
      var key = this.$route.name + ":colsettings";
      let colSettings = Vue.ls.get(key);
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = [];
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.dataIndex);
        });
        this.settingColumns = allSettingColumns;
        this.columns = this.defColumns;
      } else {
        this.settingColumns = colSettings;
        const cols = this.defColumns.filter((item) => {
          if (item.key == "rowIndex" || item.dataIndex == "action") {
            return true;
          }
          if (colSettings.includes(item.dataIndex)) {
            return true;
          }
          return false;
        });
        this.columns = cols;
      }
    },

    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ":colsettings";
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000);
      this.settingColumns = checkedValues;
      const cols = this.defColumns.filter((item) => {
        if (item.key == "rowIndex" || item.dataIndex == "action") {
          return true;
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true;
        }
        return false;
      });
      this.columns = cols;
    },
    onClearSelected() {
      this.selectedRowKeys = [];
      this.selectionRows = [];
      this.selectedMainId = "";
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedMainId = selectedRowKeys[0];
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!");
        return;
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      this.onClearSelected();
      var params = this.getQueryParams(); //查询条件
      this.loading = true;
      // getAction(this.url.list, params).then((res) => {
      //   if (res.success) {
      //     this.dataSource = res.data.records;
      //     this.ipagination.total = res.data.total;
      //   }
      //   if (res.code === 510) {
      //     this.$message.warning(res.msg);
      //   }
      //   this.loading = false;
      // });
    },
    // 处理车间数据函数
  getWorkrooms(auth){
		var dutyDtos=auth.dutyDtos;
    var workroomnos=new Array();
		for (var i = 0; i < dutyDtos.length; i++) {
      var temp=dutyDtos[i]
      var elment=this.getWorkroomItem(workroomnos,temp.workroomno);
			if(elment==null){
				elment={
					workroomno:temp.workroomno,
					workroomname:temp.workroomname,
					lines:new Array()
				}
				workroomnos.push(elment);
			}
			var lineElement={
				lineno:temp.lineno,
        linename:temp.linename,
        classno:temp.classno,
        classname:temp.classname,
			};
			elment.lines.push(lineElement);

		}
		return workroomnos;
	},
    // 处理车间数据函数
	 getWorkroomItem(workroomnos,workroomno) {
		var result=null;
		for (var i = 0; i < workroomnos.length; i++) {
			var item=workroomnos[i];
			if(workroomno===item.workroomno){
				result=item;
				break;
			}
		}
		return result;
	},
  },
};
</script>
<style scoped lang="less">
</style>